package com.report.common;

import com.report.TemplateType;
import com.report.Tools;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class DbDataSetLoader implements DataSetLoader {

    private static final Logger logger = LoggerFactory.getLogger(DbDataSetLoader.class);
    private final DataSource dataSource;

    @Override
    public List<DataSet> load(TemplateType type, List<String> nameList) {
        StringBuilder sql = new StringBuilder("SELECT name,type,data FROM generic_report_dataset WHERE 1=1");
        if (CollectionUtils.isNotEmpty(nameList)) {
            sql.append(" and name in (");
            for (int i = 0; i < nameList.size(); i++) {
                if (i > 0) sql.append(",");
                sql.append("'").append(nameList.get(i)).append("'");
            }
            sql.append(")");
        }
        if (Objects.nonNull(type)) {
            sql.append(" and (category=0 OR category=");
            sql.append(type.getCode());
            sql.append(")");
        }
        try {
            List<Map<String, Object>> result = Tools.dbQuery(dataSource, sql.toString());
            List<DataSet> dataSets = new ArrayList<>();
            for (Map<String, Object> item : result) {
                DataSet dataSet = new DataSet();
                Object temp = item.get("type");
                dataSet.setType(DataSetType.get(Integer.parseInt(temp+"")));
                dataSet.setName((String) item.get("name"));
                Object data = item.get("data");
                Class<?> clz = data.getClass();
                if ("NCLOB".equals(clz.getSimpleName())) {
                    Method method = clz.getMethod("stringValue");
                    String dataStr = (String) method.invoke(data);
                    dataSet.setData(dataStr);
                } else
                    dataSet.setData((String) data);
                dataSets.add(dataSet);
            }
            return dataSets;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return null;
    }

    public DbDataSetLoader(DataSource dataSource) {
        this.dataSource = dataSource;
    }

}
